/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package panels;

import java.awt.Color;
import java.awt.KeyEventPostProcessor;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
import src.CommandNames;

/**
 *
 * @author JMix
 */
public class VistaMallaNueva extends javax.swing.JDialog {
    
    private String nombre;
    private int cantidadSemestres;

    /**
     * Creates new form VistaMallaNueva
     */
    public VistaMallaNueva(java.awt.Frame parent, boolean modal)
    {
        super(parent, modal);
        this.nombre = "";
        this.cantidadSemestres = 0;
        initComponents();
        this.textNombreMalla.setText("");
        this.textCantidadSemestres.setText("");
        super.setLocationRelativeTo(parent);
        
        KeyboardFocusManager kb = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        kb.addKeyEventPostProcessor(new KeyEventPostProcessor(){
            public boolean postProcessKeyEvent(KeyEvent e){
                if (e.getKeyCode() == KeyEvent.VK_ESCAPE && this != null)
                    dispose();
                    return false;
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        textNombreMalla = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        textCantidadSemestres = new javax.swing.JTextField();
        btnCancelar = new javax.swing.JButton();
        btnAceptar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Crear nueva malla");
        setResizable(false);

        jLabel1.setText("(*)Nombre de la malla:");

        textNombreMalla.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textNombreMallaKeyPressed(evt);
            }
        });

        jLabel2.setText("(*)Cantidad de años:");

        textCantidadSemestres.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textCantidadSemestresKeyPressed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textNombreMalla, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textCantidadSemestres, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar)))
                .addContainerGap(14, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(textNombreMalla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textCantidadSemestres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnAceptar))
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        if (this.validarDatos()){
            this.nombre = textNombreMalla.getText();
            this.cantidadSemestres  = Integer.parseInt(textCantidadSemestres.getText());
            super.setVisible(false);
        }
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void textNombreMallaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textNombreMallaKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
            this.btnAceptarActionPerformed(null);
    }//GEN-LAST:event_textNombreMallaKeyPressed

    private void textCantidadSemestresKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textCantidadSemestresKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER)
            this.btnAceptarActionPerformed(null);
    }//GEN-LAST:event_textCantidadSemestresKeyPressed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed
    
    @Override
    public void setVisible(boolean b){
        this.limpiarCampos();
        super.setVisible(b);
    }
    public String getNombre(){
        return this.nombre;
    }
    
    public int getDuracion(){
        return this.cantidadSemestres;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VistaMallaNueva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VistaMallaNueva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VistaMallaNueva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VistaMallaNueva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                VistaMallaNueva dialog = new VistaMallaNueva(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField textCantidadSemestres;
    private javax.swing.JTextField textNombreMalla;
    // End of variables declaration//GEN-END:variables

    
    
    public void resetearValidacion(){
        this.jLabel1.setForeground(Color.black);
        this.jLabel2.setForeground(Color.black);

    }
    /**
     * Método que verifica la factibilidad de los campos iniciales para un nuevo proyecto.
     * @return Retorna un booleano. True si los campos están validos, false si no lo están.
     */
    private boolean validarDatos() {
        
        //Volvemos los componentes de aviso en su modo predeterminado.
        this.resetearValidacion();
        
        //Creamos la bandera para saber si los campos son validos.
        boolean bandera = true;
        boolean flag1 = false;
        boolean flag2 = false;
        
        //Verificamos si el nombre de la malla es valido, de lo contrario mostramos un mensaje de aviso.
        if (this.textNombreMalla.getText().equals("")){   
            this.jLabel1.setForeground(Color.red);//Volvemos color rojo el jLabel de nombre malla.
            bandera = false;
            flag1 = true;
        }
        //Obtenemos el largo de la cantidad de semestres.
        int aux = this.textCantidadSemestres.getText().length();
        //Verificamos si se ingresó algun valor, de lo contrario mostraremos un mensaje de aviso.
        if (aux == 0){
            this.jLabel2.setForeground(Color.red);//Volvemos color rojo el jLabel de cantidad de niveles.
            bandera = false;
            flag1 = true;
        }
        else{
            //Verificamos si lo ingresado en cantidad de Semestres es un entero.
            for (int i=0; i<aux; i++){
                if(!(this.textCantidadSemestres.getText().charAt(i) >= '0' && this.textCantidadSemestres.getText().charAt(i) <= '9')){
                    this.jLabel2.setForeground(Color.red);//Volvemos color rojo el jLabel de cantidad de niveles.
                    bandera = false;
                    flag2 = true;
                    break;
                }
            }
            
            if(!flag2){
                int aux2 = Integer.parseInt(this.textCantidadSemestres.getText());
                if( aux2 <= 0 || aux2 >8){
                    this.jLabel2.setForeground(Color.red);//Volvemos color rojo el jLabel de cantidad de niveles.
                    bandera = false;
                    flag2 = true;
                }
                
            }

            
        }
        if( flag1 && flag2){
             JOptionPane.showMessageDialog(this, "Los campos con (*) son obligatorios."+ "\n" +"Cantidad de años debe ser un valor entero mayor a cero.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
        else if(flag1){
            JOptionPane.showMessageDialog(this, "Los campos con (*) son obligatorios.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
        else if(flag2){
            JOptionPane.showMessageDialog(this,"Cantidad de años debe ser un valor entero mayor a cero y menor a nueve.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
        
        //Si hay algun dato invalido retornamos un false.
        if (!bandera){
            return false;
        }
        return true;
    }

    private void limpiarCampos() {
        this.textNombreMalla.setText("");
        this.textCantidadSemestres.setText("");
    }

    public boolean esValido() {
        if (!this.nombre.isEmpty() && this.cantidadSemestres > 0)
            return true;
        return false;
    }
}
